package repository

import (
	"context"
	"webook/pkg/logger"
	"webook/search/domain"
	"webook/search/repository/dao"
)

type articleSearchRepository struct {
	dao  dao.ArticleDAO
	tags dao.TagDAO
	l    logger.LoggerV1
}

func NewArticleSearchRepository(dao dao.ArticleDAO, tags dao.TagDAO, l logger.LoggerV1) ArticleSearchRepository {
	return &articleSearchRepository{
		dao:  dao,
		tags: tags,
		l:    l,
	}
}

func (repo *articleSearchRepository) InputArticle(ctx context.Context, msg domain.Article) error {
	return repo.dao.InputArticle(ctx, repo.domainToEntity(msg))
}

func (repo *articleSearchRepository) SearchArticle(ctx context.Context, uid int64, expression []string) ([]domain.Article, error) {
	ids, err := repo.tags.Search(ctx, uid, "article", expression)
	if err != nil {
		return []domain.Article{}, err
	}

	arts, err := repo.dao.Search(ctx, ids, expression)
	if err != nil {
		return []domain.Article{}, err
	}

	res := make([]domain.Article, 0, len(arts))
	for _, art := range arts {
		res = append(res, repo.entityToDomain(art))
	}

	return res, nil
}

func (repo *articleSearchRepository) domainToEntity(art domain.Article) dao.Article {
	return dao.Article{
		Id:      art.Id,
		Title:   art.Title,
		Status:  art.Status,
		Content: art.Content,
		Tags:    art.Tags,
	}
}

func (repo *articleSearchRepository) entityToDomain(art dao.Article) domain.Article {
	return domain.Article{
		Id:      art.Id,
		Title:   art.Title,
		Status:  art.Status,
		Content: art.Content,
		Tags:    art.Tags,
	}
}
